(function ($) {
    "use strict";
    var in_time = 100,
        out_time = 100;

    var Tooltip = function (element) {
        this.cursor_position = {top: 0, left: 0};
        this.$e = $(element);
        var $tip = this.$e.siblings('.tooltip'),
            self = this;
        if ($tip.length === 0) {
            $tip = $("<div class=\"tooltip\"></div>")
                .text(this.$e.data("title"))
                .insertAfter(this.$e);
        }

        this.$tip = $tip.hide();

        this.$e.mouseenter(function (e) {
            self.cursor_position = {
                top: e.clientY,
                left: e.clientX
            };
        });

        var toggle = function (action, ifDisplay, duration) {
            return function () {
                var tracking = "do_ing_" + action;
                if ($tip.css("display") === ifDisplay && !self[tracking]) {
                    self[tracking] = true;
                    if (action === "fadeIn") {
                        $tip.css(self.cursor_position);
                    }
                    $tip[action](duration, function () {
                        self[tracking] = false;
                    });
                }
            };
        };

        this.$e.hover(toggle("fadeIn", "none", 300), toggle("fadeOut", "block", 200));

    };


    $.fn.tooltip = function () {
        return this.each(function () {
            if (!$.data(this, "tooltip")) {
                $.data(this, new Tooltip(this));
            }
        });
    };

    $(function () {
        $('[title]').each(function () {
            var $a = $(this);
            $a.attr('data-title', $a.attr('title')).removeAttr('title');

        });

        $('[data-title]').tooltip();
    });

}(window.jQuery));